#include "albumdao.h"
#include "album.h"
#include "databasemanager.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QStringList>
#include <QVariant>

using namespace std;

AlbumDao::AlbumDao(QSqlDatabase &database):
    m_database(database)
{

}

void AlbumDao::init() const
{
    if( !m_database.tables().contains("albums") ) {
        QSqlQuery query(m_database);
        query.exec("CREATE TABLE albums (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");
    }
}

void AlbumDao::add_album(Album &album) const
{
    QSqlQuery query(m_database);
    query.prepare("INSERT INTO albums (name) VALUES (:name)");
    query.bindValue(":name", album.name());
    query.exec();
    album.set_id(query.lastInsertId().toInt());
}

void AlbumDao::updateAlbum(const Album &album) const
{
    QSqlQuery query(m_database);
    query.prepare("UPDATE albums SET name = :name WHERE id = :id");
    query.bindValue(":name", album.name());
    query.bindValue(":id", album.id());
    query.exec();
}

void AlbumDao::removeAlbum(int id) const
{
    QSqlQuery query(m_database);
    query.prepare("DELETE FROM albums WHERE id = :id");
    query.bindValue(":id", id);
    query.exec();
}

std::unique_ptr<std::vector<std::unique_ptr<Album> > > AlbumDao::albums() const
{
    QSqlQuery query("SELECT * FROM albums", m_database);
    query.exec();

    auto list = std::make_unique<std::vector<std::unique_ptr<Album>>>();
    while(query.next()) {
        auto album = std::make_unique<Album>();
        album->set_id(query.value("id").toInt());
        album->set_name(query.value("name").toString());
        list->push_back(move(album));
    }
    return list;
}
